package com.backend.aop;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import com.backend.entity.OperateLog;
import com.backend.mapper.OperateLogMapper;
import com.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Around("@annotation(com.backend.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //操作人id
        //获取请求头中的jwt令牌，解析获得登录人id
        String jwt = request.getHeader("Authorization");

        Integer operator = (Integer) JwtUtil.parseToken(jwt).get("id");

        //操作时间
        LocalDateTime time = LocalDateTime.now();

        //操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        //方法参数
        Object[] args = joinPoint.getArgs();
        String methodParam = Arrays.toString(args);


        long begin = System.currentTimeMillis();
        //调用原始目标方法
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        //返回值
        String returnValue = result.toString();

        Long usedTime = end - begin;


        //记录操作日志
        OperateLog operateLog = new OperateLog(null,operator,time,usedTime,className,methodName,methodParam,returnValue);
        operateLogMapper.logInsert(operateLog);
        log.info("aop记录操作日志: {}",operateLog);
        return result;
    }
}